<?php
declare (strict_types = 1);

namespace app\controller\backend\region;

use app\validate\common\region\RegionValidate;
use think\App;
use think\facade\View;
use think\Request;
use think\response\Json;
use think\db\exception\DbException;
use app\controller\backend\BackendController;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use app\service\logic\backend\region\RegionService;

class RegionController extends BackendController
{
    protected $service;

    public function __construct(App $app, RegionService $service)
    {
        parent::__construct($app);

        $this->service = $service;
    }

    /**
     * 显示资源列表
     *
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function index()
    {
        $params = $this->request->param();
        $search_fields = $this->service->getSearchColumn();
        $search = request()->only($search_fields);

        $this->validate($params, RegionValidate::class . '.index');

        $result = $this->service->getList($params, $search_fields, $search);
        return amis($result);
    }

    /**
     * 下拉菜单无分页
     *
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function options()
    {
        $params = $this->request->param();
        $search_fields = $this->service->getSearchColumn();
        $search = request()->only($search_fields);

        $result = $this->service->getOptions($params, $search_fields, $search);
        return amis($result);
    }

    /**
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function chained()
    {
        $params = $this->request->param();
        $search_fields = $this->service->getSearchColumn();
        $search = request()->only($search_fields);
        $search['p_code'] = !isset($search['p_code']) || empty($search['p_code']) ? '0' : $search['p_code'];

        $result = $this->service->getOptions($params, $search_fields, $search);
        $result = empty($result) ? null : $result;
        return amis($result);
    }

    /**
     * @return Json
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function read()
    {
        $params = $this->request->param();
        $result = $this->service->getSimpleDetail($params);
        return amis($result);
    }
}
